<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索 -->
          <el-input
            v-model="querInfo.query"
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = !addDialogVisible"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>

        <el-table-column label="邮箱" prop="email"> </el-table-column>

        <el-table-column label="电话" prop="mobile"> </el-table-column>

        <el-table-column label="角色" prop="role_name"> </el-table-column>

        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- /修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>

            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"


            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              @click="setRole(scope.row)"

              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

<!-- 分配权限区域 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRightDialogVisible"
  width="50%"
  @close="setRoleDialogClosed"
  >
  <!-- <span>这是一段信息</span> -->
  <div>
  <p>当前用户：{{userinfo.username}}</p>
  <p>当前角色： {{userinfo.role_name}}</p>
  <p>分配新角色：
 <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>


  </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>


    <!-- 添加对话框 -->
    <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="30%">
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editDialogClosed"
>
    <el-form ref="editfromRef" :model="editfrom" :rules="editfromRules" label-width="70px">
  <el-form-item label="用户名">
    <el-input v-model="editfrom.username" disabled></el-input>
  </el-form-item>

   <el-form-item label="邮箱" prop="email">
    <el-input v-model="editfrom.email" ></el-input>
  </el-form-item>

   <el-form-item label="手机号" prop="mobile">
    <el-input v-model="editfrom.mobile" ></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    return {
      input: "",
      //获取用户列表参数对象
      querInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框显示隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3-10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 10, message: "密码在3-10个字符之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { min: 3, max: 10, message: "邮箱在3-10个字符之间", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入用户手机号", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "手机号在5-10个字符之间",
            trigger: "blur",
          },
        ],
      },
        // 修改对话框的显示隐藏
      editDialogVisible:false,
      //查询到的用户信息对象
      editfrom:{},
      editfromRules:{
      email:[
          { required: true, message: "请输入邮箱名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "邮箱名长度在3-10个字符之间",
            trigger: "blur",
          },
      ],
       mobile:[
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "手机长度在3-10个字符之间",
            trigger: "blur",
          },
      ]
      },
      setRightDialogVisible:false, //控制分配角色对话框的显示和隐藏
      userinfo:{},//需要被分配角色的用户信息
      rolesList:[], //所有角色数据列表
      selectedRoleId:''//已选择的角色值
      
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.querInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPath) {
      this.querInfo.pagenum = newPath;
      this.getUserList();
    },
    async userStateChanged(userinfo) {
      // console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("修改失败");
      }
      this.$message.success("更新用户成功");
    },
    //监听添加用户对话框关闭事件
    addDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    // 点击添加用户
    addUser(){
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid) this.$message.error("添加失败")
       const {data:res}= await this.$http.post('/users',this.addForm)

       if(res.meta.status != 201){
         this.$message.error("添加失败");
       }
      this.$message.success("添加成功");
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = !this.addDialogVisible


      })
    },
    // 展示编辑用户对话框
   async showEditDialog(id){
      const {data:res} = await this.$http.get('/users/'+id)
      if(res.meta.status != 200){
        return this.$message.error('查询信息失败')
      }

      this.editfrom = res.data
      console.log(this.editfrom);
        this.editDialogVisible=!this.editDialogVisible
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed(){
      this.$refs.editfromRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo(){
      this.$refs.editfromRef.validate(async valid=>{
        if(!valid){
          return
        }

        //发起请求
      const {data:res} = await this.$http.put('users/'+this.editfrom.id,{
          email:this.editfrom.email,
          mobile:this.editfrom.mobile
        })
        if(res.meta.status != 200){
          return this.$message.error('更新用户信息失败')
        }
        this.editDialogVisible=false
        this.getUserList()
        this.$message.success('更新成功')
      })
    },
    //删除用户信息
  async  removeUserById(id){
      // console.log(id);
      //询问是否删除
     const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err =>{return err})
        //点击了取消，就算了
        if(confirmResult != 'confirm'){
          return this.$message.info('已取消')
        }
     const{data:res} = await this.$http.delete('users/'+id)
     if(res.meta.status != 200){
       this.$message.error('删除用户失败')
     }

     this.$message.success('删除成功')
      this.getUserList()

    },
      //展示分配角色对话框
   async setRole(userinfo){
      
      this.userinfo = userinfo
    const {data:res} = await this.$http.get('roles')
    if(res.meta.status != 200){
      return this.$message.error('获取角色列表失败')
    }
    this.rolesList = res.data
      this.setRightDialogVisible = !this.setRightDialogVisible

    },
    //点击确定分配角色
  async  saveRoleInfo(){
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
   const {data:res}=  await this.$http.put(`users/${this.userinfo.id}/role`,{
        rid:this.selectedRoleId
      })
      if(res.meta.status != 200){

        return this.$message.error('更新角色失败')
      }

      this.$message.success('更新角色成功')

      this.getUserList()
      this.setRightDialogVisible = false
    },
    //监听分配角色对话框关闭事件
    setRoleDialogClosed(){
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>